﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Broker.Service.EntityModel;
using BrokerBase.Lib.Client;
using System.Data;
using BrokerBase.Lib.Tool;
using System.Data.EntityClient;

namespace Broker.Service.Model
{
    public class ClientUtil
    {
        public static bool IsNameExist(string name,broker30Entities entity)
        {

            Broker.Service.EntityModel.Sale_Client client = entity.Sale_Client.FirstOrDefault(p => p.Name == name);

            return client == null ? false : true;

        }

        public static bool IsTrial(Sale_Client client,broker30Entities entity)
        {

            Sale_ActiveCode ac = entity.Sale_ActiveCode.FirstOrDefault(p => p.RegistrantId == client.Id && p.Edition > (int)EditionType.Evaluation);

            return ac == null ? true : false;
                

        }

        public static void UpdateScore(Sale_Client client,decimal score, broker30Entities entity,IDbTransaction tx)
        {
            try
            {
                string sql = string.Format("update Sale_Client set TotalScore=TotalScore+{0} where id={1}", score, client.Id);
                IDbCommand cmd = entity.Connection.CreateCommand();
                
                cmd.Transaction = tx;
                cmd.CommandText = sql;
                cmd.ExecuteNonQuery();
                
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public static Score_ScoreRecord CreateOrUpdateScoreRecord(Sale_Client client, Sale_Client provider,Score_ScoreRecordType recordType,
            Sale_ActiveCodeReg reg, Sale_ActiveCode code,  Score_Rule rule, int level, string description, broker30Entities entity)
        {
            Score_ScoreRecord record = entity.Score_ScoreRecord.FirstOrDefault(p => p.ClientId == client.Id && p.ProviderId == provider.Id);

            bool isNew = false;

            if (record == null)
            {
                record = new Score_ScoreRecord();
                isNew = true;
            }

            record.ScoreTime = DateTimeUtil.ChinaStandardTime;
            record.ClientId = client.Id;
            record.RecordTypeId = recordType.Id;
            record.RegId = reg.Id;
            record.ProviderId = provider.Id;
            record.IsTrial = code.Edition == (int)EditionType.Evaluation ? true : false;
            record.OppositeLevel = level;
            record.Description = description;

            //只有大于规则最小金额才计算积分
            if (rule != null && code.Amount >= rule.MinAmount)
                record.Score = rule.Score * (decimal)Math.Pow((double)rule.Scale, level - 1);//计算积分

            if (isNew)
            {
                entity.Score_ScoreRecord.AddObject(record);
            }

            entity.SaveChanges();

            return record;
        }

        public static bool VerifyLicense(RegistrantInfo registrantInfo, TerminalInfo terminalInfo, broker30Entities entity, out string message)
        {
            try
            {
                message = string.Empty;

                Sale_ActiveCodeReg codeReg =(from reg in entity.Sale_ActiveCodeReg 
                        join code in entity.Sale_ActiveCode on reg.ActiveCodeId  equals code.Id
                        join c in entity.Sale_Client on code.RegistrantId equals c.Id
                      where c.Name==registrantInfo.UserName &&
                        (
                            reg.DISKSerialNo==terminalInfo.DISKSerialNo ||
                            reg.MACSerialNo==terminalInfo.MACSerialNo ||
                            reg.MBSerialNo==terminalInfo.MBSerialNo
                        )
                      select reg).FirstOrDefault();

                return codeReg != null;

            }
            catch (Exception er)
            {
                message = er.Message;
                return false;
            }
        }

        public static Sale_ActiveCode GetInviteCode(Sale_Client presenter, broker30Entities entity)
        {
            Sale_ActiveCode ac = null;

            IDbTransaction tx = null;

            try
            {
                entity.Connection.Open();
                tx = entity.Connection.BeginTransaction();


                DateTime dt = DateTimeUtil.ChinaStandardTime;

                ac = ActiveCodeUtil.CreateActiveCode(EditionType.Evaluation, 1, 30);

                ac.PresenterId = presenter.Id;
                ac.SendTime = dt;

                entity.Sale_ActiveCode.AddObject(ac);
                entity.SaveChanges();

                //ActiveCodeSend send = ac.CreateSend();
                Sale_ActiveCodeSend send = new Sale_ActiveCodeSend();
                send.ActiveCodeId = ac.Id;
                send.MailSubject = "激活码";
                send.MailBody = string.Empty;
                send.SenderId = presenter.Id;
                send.SendTime = dt;

                entity.Sale_ActiveCodeSend.AddObject(send);

                presenter.InviteCodeQty--;

                entity.SaveChanges();

                tx.Commit();
            }
            catch (Exception ex)
            {
                if (tx!=null)
                    tx.Rollback();

                throw ex;
            }

            return ac;
        }
    }
}